﻿using LPLS.Commons.Enums;
using LPLS.DBEntities.OEEModule.OEEModels.DataStatisticModels;
using LPLS.DBInterface.OEEModule.OEEModels.DataStaticsticModels;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStatisticsChartModule.ViewModels
{
    public  class AlarmDataStatisticsChartViewModel:BindableBase
    {


        IAlarmDataStatisticService _alarmStatisticService;

        public AlarmDataStatisticsChartViewModel(IAlarmDataStatisticService alarmDataStatisticService)
        {
            _alarmStatisticService = alarmDataStatisticService;
            DataStatisticsEvent.OnDataStatisticsEvent += DataStatisticsEvent_OnDataStatisticsEvent;
        }

        private void DataStatisticsEvent_OnDataStatisticsEvent(DataStatisticsEventModel obj)
        {
            var starttime = obj.StartTime;
            var endtime = obj.EndTime;
            var deviceid = obj.DeviceModel.ID;
            QueryData(starttime, endtime, deviceid);
        }
        private PlotModel _DeviceDataPieChartModel;
        public PlotModel DeviceDataPieChartModel
        {
            get { return _DeviceDataPieChartModel; }
            set
            {

                SetProperty(ref _DeviceDataPieChartModel, value);
            }
        }
        private PlotModel _DeviceEveryAlarmByTimeModel;
        public PlotModel DeviceEveryAlarmByTimeModel
        {
            get { return _DeviceEveryAlarmByTimeModel; }
            set
            {
                SetProperty(ref _DeviceEveryAlarmByTimeModel, value);
            }
        }
        private PlotModel _DeviceDataLineBarChartModel;
        public PlotModel DeviceDataLineBarChartModel
        {
            get { return _DeviceDataLineBarChartModel; }
            set
            {

                SetProperty(ref _DeviceDataLineBarChartModel, value);
            }
        }



        private PlotModel _LevelDataLineBarChartModel;

        public PlotModel LevelDataLineBarChartModel
        {
            get { return _LevelDataLineBarChartModel; }
            set { _LevelDataLineBarChartModel = value; }
        }

        /// <summary>
        /// 数据查询方法
        /// </summary>
        private void QueryData(DateTime starttime, DateTime endtime, Guid  deviceid)
        {
            ///获取到了数据
            var data = _alarmStatisticService.GetData(deviceid,starttime, endtime);

            #region  对数据进行筛选

            QueryAlarmDataPieChartModelData(data);
            QueryAlarmEveryAlarmByTimeToLineBar(data);
            QueryAlarmDataLineBarChartModel(data);
            QuaryDeviceDataToDataGid(data);
            QuaryLevelDataLineBarChartModel(data);
            #endregion
        }


        private void LoadTestData()
        {

            List<AlarmDataStatistic> li = new List<AlarmDataStatistic>();

            li.Add(new AlarmDataStatistic
            {
                AlarmCode = "T_Sys_XXX_3_32"



            });
        }

        /// <summary>
        /// 每种状态的时间总占比
        /// </summary>
        /// <param name="data"></param>
        private void QueryAlarmDataPieChartModelData(List<AlarmDataStatistic> data)
        {

            #region  DeviceDataPieChartModel 赋值
            var tmp = new PlotModel { Title = "设备各状态占比统计", Subtitle = "" };

            PieSeries series4 = new PieSeries { Title = "时长占比（单位：分）", StrokeThickness = 1, InsideLabelPosition = 0.5 };
            var groupedData = data.GroupBy(d => d.Status).Select(g => new { Status = g.Key, TotalTime = g.Sum(d => d.TotalSecondTime) / 60 }).ToList();

            Parallel.ForEach(groupedData, item =>
            {


                series4.Slices.Add(new PieSlice(item.Status.GetDescription(), item.TotalTime)
                {
                    IsExploded = true,

                });
            });

            Legend l = new Legend();
            l = GetLanguage();
            tmp.Legends.Add(l);
            DeviceDataPieChartModel = tmp;


            #endregion

        }
        /// <summary>
        /// 查询每一种报警状态在该时间段内的详细情况
        /// </summary>
        /// <param name="data"></param>
        private void QueryAlarmEveryAlarmByTimeToLineBar(List<AlarmDataStatistic> data)
        {
            var model = new PlotModel();
            model.Title = "该时间段的不同状态详细情况";
            //1.先把所有的开始时间获取到作为X轴
            var xdata = data.GroupBy(d => d.StartTime)
            .Select(g => new { Date = g.Key })
            .OrderBy(d => d.Date)
            .ToList();
            List<string> xArry = new List<string>();
            foreach (var item in xdata)
            {
                xArry.Add(item.Date.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            var categoryAxis = new CategoryAxis
            {
                Title = "时间",
                ItemsSource = xArry,
                Position = AxisPosition.Bottom,
                Key = "x1"
            };
            var valueAxis1 = new LinearAxis
            {
                Title = "持续时间 单位（分钟）",
                Position = AxisPosition.Left,
                MinimumPadding = 0.06,
                MaximumPadding = 0.06,
                ExtraGridlines = new[] { 0d },
                Key = "y1"
            };
            model.Axes.Add(categoryAxis);
            model.Axes.Add(valueAxis1);
            var series = new List<BarSeries>();


            var groupAlarmMess = data.Where(e=>!string.IsNullOrEmpty(e.AlarmMessage)).ToList().GroupBy(g=>g.AlarmCodeName);
            ///创建series 根据报警提示创建
            foreach (var item in groupAlarmMess)
            {
                var barmodel = new BarSeries() { XAxisKey = "y1", YAxisKey = "x1", Title = item.Key };
                series.Add(barmodel);
            }
            var groupdata = data.GroupBy(d => d.StartTime).ToList();
            foreach (var item in groupdata)
            {
                var key = item.Key.ToString("yyyy-MM-dd HH:mm:ss");//在这个X轴下找数据
                foreach (var item2 in item)
                {
                    var status = item2.AlarmCodeName;
                   // var des = StatusEnumHelper.GetDescription(status);
                    var serial = series.Where(e => e.Title == status).ToList().FirstOrDefault() ?? null;
                    if (serial != null)
                    {
                        serial.Items.Add(new BarItem() { Value = item2.TotalSecondTime / 60 });
                    }
                }
            }
            foreach (var item in series)
            {
                model.Series.Add(item);
            }

            Legend l = new Legend();
            l = GetLanguage();
            model.Legends.Add(l);
           DeviceEveryAlarmByTimeModel = model;
        }
        /// <summary>
        /// 查找各部件统计图
        /// </summary>
        /// <param name="data"></param>
        private void QueryAlarmDataLineBarChartModel(List<AlarmDataStatistic> data)
        {

            var model = new PlotModel { Title = "报警各状态占比统计", Subtitle = "" };

            var groupedData = data.GroupBy(d => d.Status).Select(g => new { Status = g.Key, TotalTime = g.Sum(d => d.TotalSecondTime) / 60 }).ToList();

            var xArry = new List<string>();

            var (enumValues, enumValueInts, descriptions) = StatusEnumHelper.GetEnumCollections();

            foreach (var item in descriptions)
            {
                xArry.Add(item);
            }
            var categoryAxis = new CategoryAxis
            {
                Title = "状态",
                ItemsSource = xArry,
                Position = AxisPosition.Bottom,
                Key = "x1"
            };
            var valueAxis1 = new LinearAxis
            {
                Title = "持续时间 单位（分钟）",
                Position = AxisPosition.Left,
                MinimumPadding = 0.06,
                MaximumPadding = 0.06,
                ExtraGridlines = new[] { 0d },
                Key = "y1"
            };

            model.Axes.Add(categoryAxis);
            model.Axes.Add(valueAxis1);
            var series = new List<BarSeries>();
            foreach (var item in descriptions)
            {

                var barmodel = new BarSeries() { XAxisKey = "y1", YAxisKey = "x1", Title = item };
                series.Add(barmodel);

            }

            Parallel.ForEach(groupedData, item =>
            {

                var status = item.Status;
                var des = StatusEnumHelper.GetDescription(status);
                var serial = series.Where(e => e.Title == des).ToList().FirstOrDefault() ?? null;
                if (serial != null)
                {
                    serial.Items.Add(new BarItem() { Value = item.TotalTime });

                }

            });
            foreach (var item in series)
            {
                model.Series.Add(item);
            }
            Legend l = new Legend();
            l = GetLanguage();
            model.Legends.Add(l);
            DeviceDataLineBarChartModel = model;
        }
        private void QuaryDeviceDataToDataGid(List<AlarmDataStatistic> data)
        {

            QueryDataList = new ObservableCollection<AlarmDataStatistic>(data);

        }



        /// <summary>
        /// 根据等级划分统计图 leve
        /// </summary>
        /// <param name="data"></param>
        private void QuaryLevelDataLineBarChartModel(List<AlarmDataStatistic> data) 
        {

            var model = new PlotModel();
            model.Title = "时间段的不同等级详细情况";
            //1.先把所有的开始时间获取到作为X轴
            var xdata = data.GroupBy(d => d.StartTime)
            .Select(g => new { Date = g.Key })
            .OrderBy(d => d.Date)
            .ToList();
            List<string> xArry = new List<string>();
            foreach (var item in xdata)
            {
                xArry.Add(item.Date.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            var categoryAxis = new CategoryAxis
            {
                Title = "时间",
                ItemsSource = xArry,
                Position = AxisPosition.Bottom,
                Key = "x1"
            };
            var valueAxis1 = new LinearAxis
            {
                Title = "持续时间 单位（分钟）",
                Position = AxisPosition.Left,
                MinimumPadding = 0.06,
                MaximumPadding = 0.06,
                ExtraGridlines = new[] { 0d },
                Key = "y1"
            };
            model.Axes.Add(categoryAxis);
            model.Axes.Add(valueAxis1);
            var series = new List<BarSeries>();


            var groupAlarmMess = data.ToList().GroupBy(g => g.AlarmLevel);
            ///创建series 根据报警提示创建
            foreach (var item in groupAlarmMess)
            {
                var barmodel = new BarSeries() { XAxisKey = "y1", YAxisKey = "x1", Title = "报警等级-"+ item.Key };
                series.Add(barmodel);
            }
            var groupdata = data.GroupBy(d => d.StartTime).ToList();
            foreach (var item in groupdata)
            {
                var key = item.Key.ToString("yyyy-MM-dd HH:mm:ss");//在这个X轴下找数据
                foreach (var item2 in item)
                {
                    var status = "报警等级-" + item2.AlarmLevel;
                    // var des = StatusEnumHelper.GetDescription(status);
                    var serial = series.Where(e => e.Title == status).ToList().FirstOrDefault() ?? null;
                    if (serial != null)
                    {
                        serial.Items.Add(new BarItem() { Value = item2.TotalSecondTime / 60 });
                    }
                }
            }
            foreach (var item in series)
            {
                model.Series.Add(item);
            }

            Legend l = new Legend();
            l = GetLanguage();
            model.Legends.Add(l);
            LevelDataLineBarChartModel = model;



        }

        private Legend GetLanguage()
        {
            Legend legend = new Legend()
            {

                LegendBorder = OxyColors.Black,
                LegendBackground = OxyColor.FromAColor(200, OxyColors.White),
                LegendPosition = LegendPosition.LeftTop,
                LegendPlacement = LegendPlacement.Outside,
                LegendOrientation = LegendOrientation.Horizontal,
                LegendItemOrder = LegendItemOrder.Normal,
                LegendItemAlignment = HorizontalAlignment.Left,
                LegendSymbolPlacement = LegendSymbolPlacement.Right,

            };

            return legend;

        }

        private ObservableCollection<AlarmDataStatistic> _QueryDataList;
        public ObservableCollection<AlarmDataStatistic> QueryDataList
        {
            get { return _QueryDataList; }
            set
            {

                SetProperty(ref _QueryDataList, value);
            }
        }




    }
}
